<?php

namespace common\services\cms;

use common\services\BaseService;
use common\repositories\cms\ArticleRepository;
use common\repositories\cms\ArticleOrgRepository;
use common\repositories\cms\DirRepository;
use common\entities\cms\ArticleEntity;
use common\services\cms\DirService;

class ArticleService extends BaseService {

    public $_ArticleRepository;
    public $_DirRepository;
    
    public function __construct(ArticleRepository $ArticleRepository, DirRepository $DirRepository) {
        $this->_ArticleRepository = $ArticleRepository;
        $this->_DirRepository = $DirRepository;
    }
    
    /**
     * 更新文章点击数
     * @param type $articleId
     */
    public function updatePv ($id) {
        if ( ! empty($id)) {
            $this->_ArticleRepository->updatePv($id);
        }
    }
    
    public function updateShareNum($id) {
        if ( ! empty($id)) {
            $this->_ArticleRepository->updateShareNum($id);
        }        
    }
    
    public function saveArticle ($model) {

        if($model->dirId&&in_array($model->dirId,ArticleOrgRepository::$CHECK_ORG_DIRS)) {
            $transaction=ArticleEntity::getDb()->beginTransaction();
            $articleOrgRepository=\Yii::createObject(ArticleOrgRepository::className());
            if (isset($model->aId) && !empty($model->aId)) {
                //修改
                $result = $this->_ArticleRepository->updateArticle($model);
                if($result===false){
                    $transaction->rollBack();
                    return false;
                }
                $articleId=$model->aId;
            } else {
                //新增
                $result = $this->_ArticleRepository->addArticle($model);
                if(!$result){
                    $transaction->rollBack();
                    return false;
                }
                $articleId=$result;
            }
            $delResult=$articleOrgRepository->delByArticleId($articleId);
            if($delResult===false){
                $transaction->rollBack();
                return false;
            }
            $orgGuids=$model->orgGuids;
            if(!empty($orgGuids)) {
                $addResult = $articleOrgRepository->batchAdd($articleId, $orgGuids);
                if ($addResult === false) {
                    $transaction->rollBack();
                    return false;
                }
            }
            $transaction->commit();
        }else{
            if (isset($model->aId) && !empty($model->aId)) {
                //修改
                $result = $this->_ArticleRepository->updateArticle($model);
            } else {
                //新增
                $result = $this->_ArticleRepository->addArticle($model);
            }
        }
        return $result;
    }
    
    public function getArticleInfo ($aId) {
        if(empty($aId)) {
            $list = array(
                'title' => '',
                'created_by' => '',
                'author' => '',
                'link_url' => '',
                'tag' => '',
                'pv' => '0',
                'collect'=> '0',
                'image_url' => '',
                'file_url' => '',
                'file_name' => '',
                'file_url2' => '',
                'file_name2' => '',
                'file_url3' => '',
                'file_name3' => '',
                'a_id' => '',
                'content' => '',
                'dir_id' => '',
                'abstract_mode' => 1,
                'orgGuids'=>[]
            );
        }
        else {
            $list = $this->_ArticleRepository->getArticleInfo($aId);
            if(!empty($list)&&isset($list['dir_id'])&&in_array($list['dir_id'],ArticleOrgRepository::$CHECK_ORG_DIRS)) {
                /** @var ArticleOrgRepository $articleOrgRepository */
                $articleOrgRepository = \Yii::createObject(ArticleOrgRepository::className());
                $orgGuids = $articleOrgRepository->getOrgIdsBy($aId);
                if (!empty($orgGuids)) {
                    $list['orgGuids'] = $orgGuids;
                } else {
                    $list['orgGuids'] = []; //全部
                }
            }
//            $urlList = explode("@@", $list['file_url']);
//            unset($urlList[0]);
//            $list['file_url'] = $urlList;
//            $nameList = explode("@@", $list['file_name']);
//            unset($nameList[0]);
//            $list['file_name'] = $nameList;
        }
      //  var_dump($list);exit;
        return $list;
        //$dirList = $this->_DirRepository->getDirList();
    }

    /**
     * 获取文章列表
     * @param $sidx 排序字段
     * @param $sord 排序规则
     * @param $page 当前页码
     * @param $page_size 每页条数
     * @param $search 搜索关键字
     * @return 文章列表
     */
    public function getArticleAllList ($sidx, $sord, $page, $page_size, $search) {
        $updateDirIds = $this->updateDirIds();
        return $this->_ArticleRepository->getArticleAllList($sidx, $sord, $page, $page_size, $search, $updateDirIds);
    }
    
    public function getArticleList($dirId,$limit) {
        return $this->_ArticleRepository->getArticleListByDirId($dirId,$limit);
    }
    
    public function getArticleListByKeyword ($keyword, $offset=0, $limit=10) {
        $query = ArticleEntity::find();
        if (! empty($keyword)) {
            $query = $query->where(['like', 'title', $keyword])
                ->orwhere(['like', 'tag', $keyword]);
        }  
        $query = $query->andwhere(['del' => 0])
            ->andwhere(['status' => 1])
            ->offset((int)$offset*$limit)
            ->limit((int)$limit)
            ->all();  
        return $query;   
    }
    
    public function getArticleCountByKeyword ($keyword) {
        $query = ArticleEntity::find();
        if (! empty($keyword)) {
            $query = $query->where(['like', 'title', $keyword])
                ->orwhere(['like', 'tag', $keyword]);
        }  
        $query = $query->andwhere(['del' => 0]) 
            ->andwhere(['status' => 1])
            ->count();  
        return $query;   
    }   
    
    /**
     * 批量修改
     * @param type $section
     * @param type $value
     * @param type $ids
     */
    public function updateBatch ($section, $value, $str) {
        $ids = explode(':', $str);
        $idArr =$insideArr=$outsideArr= [];
        foreach ($ids as $val) {
            is_numeric($val) && $idArr[] = $val;
        }
        $dirService=new DirService();

        foreach($idArr as $id){
            $articleInfo=$this->getArticleInfo ($id);
            $dirEntity=$dirService->getDirById($articleInfo['dir_id']);
            if($dirEntity->status==1){
                $insideArr[$id]=$value;
                if($dirEntity->external_display==1){
                    $outsideArr[$id]=$value;
                }else{
                    $outsideArr[$id]=0;
                }
            }else{
                $insideArr[$id]=0;
                $outsideArr[$id]=0;
            }

        }
        return $this->_ArticleRepository->updateBatch($section, $value, $idArr,$insideArr,$outsideArr);
    }
    
    /**
     * 字段处理
     */
    public function dealField ($field) {
        $field == 'id' && $field = 'a_id';
        $field == 'dirName' && $field = 'dir_id';
        $field == 'modifiedTime' && $field = 'modified_time';
        $field == 'modifiedBy' && $field = 'modified_by';
        $field == 'edit' && $field = 'a_id';  
        return $field;
    }

    public static function existsArticleByDirId($dirId) {
        return ArticleRepository::existsArticleByDirId($dirId);
    }

    /**
     * 删除附件
     * @param $a_id string 文章ID
     * @param $url string 发奖URL
     * @return bool
     */
    public function fujianDel($a_id, $url)
    {
        return $this->_ArticleRepository->fujianDel($a_id, $url);
    }

    /**
     * 获取更新说明文章列表
     * @param $sidx string 排序字段
     * @param $sord string 排序规则
     * @param $page int 页码
     * @param $page int 每页条数
     * @param $search string 搜索关键字
     * @return srticleList array 文章列表
     */
    public function getUpdateArticleList ($sidx, $sord, $page, $page_size, $search) {
        $updateDirIds = $this->updateDirIds();
        return $this->_ArticleRepository->getUpdateArticleList($sidx, $sord, $page, $page_size, $search, $updateDirIds);
    }

    /**
     * @param $id int 文章id
     * @param $attrArray 修改字段
     * @return bool
     */
    public function updateQuickSet($id, $attrArray){
        return $this->_ArticleRepository->updateQuickSet($id, $attrArray);
    }

    /**
     * 返回所有更新墙目录
     * @return array
     */
    public function updateDirIds()
    {
        $updateDirIds =  $this->_DirRepository->getUpdateDirIds();
        $updateDirIdArray = array();
        foreach ($updateDirIds as $k => $v){
            $updateDirIdArray[] = $v['id'];
        }
        return $updateDirIdArray;
    }
}